var bpmService = {};
/**
 鎵撳紑浠诲姟浼犲叆鐨勫弬鏁�
 taskId, 浠诲姟ID
 instanceId, 瀹炰緥ID  鑽夌ǹ璇︽儏
 defId,瀹氫箟ID
 nodeId: 鑺傜偣ID
 **/
bpmService.params ;
//鍒濆鍖栧姩浣�
bpmService.init = function(params,fn){
    this.params = params;

    var dataUrl = Vue.__ctx + "/bpm/task/getTaskData";// taskId=xxx
    if(!params.taskId){
        dataUrl =  Vue.__ctx + "/bpm/instance/getInstanceData";
    }

    var defer = Vue.baseService.postForm(dataUrl,params);
    Vue.tools.getResultData(defer,function(data){
        //鍙互鍐嶈〃鍗曚腑鎵╁睍閰嶇疆閫昏緫
        data.flowRequestParam  = bpmService.getSubmitFlowParam(data);

        if(fn)fn(data);
    },"alert");

};

//鑾峰彇琛ㄥ崟鐨勬暟鎹�
bpmService.getFormData = function(custFormContext,button,postFn){
    var validateForm = "start,agree,oppose".indexOf(button.alias)!=-1;

    var formType = custFormContext.form.type;
    if(formType=='INNER'){
        var errorMsg = Vue.formService.getValidateMsg(custFormContext);
        if(errorMsg && validateForm){
            $.Dialog.alert("琛ㄥ崟鏍￠獙涓嶉€氳繃锛�"+errorMsg,7);
            return false;
        }
        return custFormContext.data;
    }
    if(formType=='FRAME'){

        // 鑾峰彇url琛ㄥ崟鐨刬frame瀵硅薄
        var iframeObj=document.getElementById("frmFrame").contentWindow;

        //灏濊瘯鏍￠獙
        try{
            if(validateForm){
                if(iframeObj.isValid() === false){
                    return false;
                }
            }
        }catch(e){}

        try {

            // 鍙栧€兼柟寮忎竴 : 灏濊瘯鐩存帴鍙栧€� , 鍦╱rl琛ㄥ崟涓坊鍔犱竴涓獁indow.getData鐨勫嚱鏁� 鐢ㄦ潵杩斿洖褰撳墠url鐨勮〃鍗曟暟鎹� ,
            // 娉ㄦ剰闇€瑕佽嚜宸辨牎楠屾暟鎹� ,濡傛灉鏍￠獙澶辫触,闇€瑕佽嚜琛屾彁绀�,骞朵笖杩斿洖false , 姣斿
            /**
             * window.getData = function(){
					if(!isValid){
						return false;
					}

					return data;
			   }
             */
            return iframeObj.getData();
        } catch (e) {

            // 鍒ゆ柇瀛愰〉闈㈡槸鍚︽湁鐩戝惉浜嬩欢 , 杩欓噷閫氳繃window.name == 'subIframeCallback'
            if(window.name != 'subIframeCallback' ){
                // 濡傛灉娌℃湁鐩戝惉,鍒欑洿鎺ヨ繑鍥�
                return {};
            }

            // 濡傛灉瀛愰〉闈㈡病鏈塯etData鍑芥暟, 鎴栬€呮槸璺ㄥ煙浜�, 鍒欓€氳繃 Html5閫氳鐨勬柟寮忚幏鍙�
            // 鍒ゆ柇鏄惁璺ㄥ煙鍙弬鑰冭繖涓摼鎺� https://blog.csdn.net/shuiya3/article/details/49490441
            var targetUrl = document.getElementById("frmFrame").src;

            // 1. 褰撳墠椤甸潰鎺ユ敹瀛愰〉闈㈢殑鏁版嵁浜嬩欢
            window.onmessage = function(e){
                e = e || event;
                var data = e.data || {};
                layer.close(layer.load());
                if( data.type == 'getData' && data.url == targetUrl ){
                    if(!data.valid){
                        // 濡傛灉鏍￠獙澶辫触,鍒欐彁绀�
                        alert("琛ㄥ崟鏍￠獙涓嶉€氳繃锛�"+ data.errorMsg);
                        return
                    }
                    var resultData = data.data;
                    postFn(button,resultData);
                }
            }

            // 2. 鐢卞綋鍓嶉〉闈㈠彂閫佽幏鍙栨暟鎹簨浠舵秷鎭粰瀛愰〉闈�
            iframeObj.postMessage({type: 'getDataReady', url: document.location.href}, targetUrl);

            // 3. 姝ゆ椂瀛愰〉闈㈤渶瑕佹帴鏀惰浜嬩欢 , 骞朵笖灏嗘暟鎹互html5閫氳鐨勬柟寮忓彂閫佸洖鏉� , 浠ｇ爜濡備笅
            /**
             *
             window.onmessage = function(e){
			  		var data = e.data || {};
			  		var valid = true;
			  		var errorMsg = "鏁版嵁涓嶈兘涓虹┖";
			  		// TODO 鏍￠獙琛ㄥ崟鐨勯€昏緫

			  		var formData = {};
			  		// TODO 鑾峰彇鏁版嵁鐨勯€昏緫

			  		if( data.type == 'getDataReady'){
						window.parent.postMessage ( {
				            type : 'getData' ,
				            url : document.location.href ,
				            valid : valid,
				            errorMsg : errorMsg,
				            data : formData
				        }, data.url );
				    }
		        }
             */

            return {waitIframeNotify:true};
        }
    }
    else{
        alert("涓嶆敮鎸佺殑琛ㄥ崟绫诲瀷:"+formType)
    }
};

// 娴佺▼鎻愪氦闇€瑕佺殑鍙傛暟
bpmService.getSubmitFlowParam = function(data){
    if(!data){
        alert("error");
        return;
    }

    if(data.task) {
        return {taskId:data.task.id,nodeId:data.task.nodeId,instanceId:data.task.instId};
    }

    if(data.instance){
        return {instanceId:data.instance.id,defId:data.instance.defId};
    }

    var initBizIdName = $.getParam("bizIdName") || "bizId";

    var defId = data.defId || this.params.defId ;

    return {
        defId: defId,
        instanceId: this.params.instanceId,
        businessKey: $.getParam(initBizIdName)
    }
}
/**
 * 娴佺▼鎸夐挳瑙ｆ瀽銆�
 * 鍏充簬鎸夐挳鏍峰紡锛屽璇濇瀹介珮灞炴€э紝涓嶅仛鍙厤缃锛屽洜涓哄墠娈垫棤娉曠粺涓€锛�
 * 浣嗘槸銆佽姹傝祫婧愯矾寰勮姹備竴鑷达紝姣斿/bpm/task/   /bpm/instance.
 * 鍓嶇紑鑷繁鍓嶆鎺у埗
 */
Vue.component('bpmButtons',{
    props: ['buttons'],
    data:function(){
        return { }
    },
    methods:{
        buttonClick : function(button){
            var ii = layer.load();

            //鎵ц鍓嶇疆js
            if(!this.execuFn(button.beforeScript)){
                layer.close(ii);
                return;
            }
            //鑾峰彇娴佺▼鏁版嵁
            var custFormContext = getCustFormComponent(this.$parent);

            //瀹㈡埛琛ㄥ崟鑷畾涔� fn:custValid 鏍￠獙
            var validateForm = "start,agree,oppose".indexOf(button.alias)!=-1;
            if(validateForm && custFormContext.custValid){
                if(custFormContext.custValid() === false){
                    layer.close(ii);
                    return;
                }
            }
            // 鑾峰彇鍦ㄧ嚎琛ㄥ崟鏁版嵁锛屽苟鏍￠獙鍐呯疆鏍￠獙
            var busData = bpmService.getFormData(custFormContext,button,this.postFn);
            if(busData === false){//鑾峰彇鏁版嵁澶辫触
                layer.close(ii);
                return;
            }

            if(!busData.waitIframeNotify){
                this.postFn(button,busData);
            }


        },
        postFn : function(button,busData){
            var ii = layer.load();
            var scope = this;
            var custFormContext = getCustFormComponent(this.$parent);
            var flowData = custFormContext.flowRequestParam;
            flowData.data = busData;

            flowData.action =  button.alias;
            flowData.extendConf = {
                'nodeId' : $.getParam("nodeId")
            };

            //鑾峰彇鏇村瀹屾垚鍔ㄤ綔閰嶇疆
            var buttonStyle = this.getButtonStyle(button.alias);

            // 鍚屾剰锛屽弽瀵圭殑鏃跺€欏彲浠ヨ嚜鍔ㄨ烦杩囧綍鍏ユ剰瑙�
            var requiredOpinion = custFormContext.configSpecified.requiredOpinion;
            if(!requiredOpinion && "oppose,agree,start".indexOf(button.alias)==-1){
                requiredOpinion = true;
            }

            if( button.configPage && requiredOpinion){
                layer.close(ii);

                var height = buttonStyle.dialogHeigth || 322;
                var width = buttonStyle.dialogWidth || 650;

                var conf = {title:button.name,url:button.configPage,height:height,width:width,passData:flowData,topOpen:false};
                conf.ok = function(index,innerWindow){
                    if(!innerWindow.isValidate())return ;
                    scope.postAction(flowData,innerWindow);
                }
                layer.close(ii);
                $.Dialog.open(conf);
            }else{
                if(!flowData.opinion){
                    flowData.opinion = button.name;
                }

                layer.close(ii);
                scope.postAction(flowData);
            }
        },
        postAction : function(flowData){
            var ii = layer.load();
            // 鎵ц鍔ㄤ綔
            var url =  Vue.__ctx + (flowData.taskId ? "/bpm/task/doAction":"/bpm/instance/doAction");
            var defer = Vue.baseService.post(url,flowData);
            var that = this;

            defer.then(function(result){
                layer.close(ii);
                // 瀛樺湪寮傚父
                if(!result.isOk){
                    //濡傛灉鏄痗onfrms 鍒欎笉鎻愮ず閿欒
                    if(!that.handConfirms(result,flowData)){
                        $.Dialog.error(result.msg);
                        console.error(result);
                    }
                    return;
                }

                $.Dialog.success(result.msg,function(){

                    //鍏抽棴绐楀彛骞跺埛鏂扮埗椤甸潰鐨勫垪琛�
                    window.setTimeout(function(){
                        try{
                            parent.layer.closeAll();
                        }catch(e){
                            window.close();
                        }
                    },10)

                    try{
                        if(window.opener && window.opener.reloadGrid){
                            window.opener.reloadGrid();
                        }
                    }catch(e){
                    }

                });


            },function(code){
                layer.close(ii);
                $.Dialog.alert("鍔犺浇澶辫触锛�"+code,2);
                console.error(code);
            })

        },
        handConfirms:function(data,flowData){
            var that = this;
            // 闇€瑕佷簩娆＄‘璁�
            if(data && data.code ==="50103"){
                $.Dialog.confirm("鑷富鍥炴敹鍒嗗彂浠诲姟鎻愮ず",data.msg,function(){
                    flowData.extendConf.confirmRecycle = true;
                    that.postAction(flowData);
                })
                return true;
            }
            return false;
        },
        execuFn : function(fnStr){
            if(!fnStr)return true;
            var parentScope = getCustFormComponent(this.$parent);

            var script = "var tempFunction = function(scope){ "+fnStr+"};"
            var result =  eval(script+"tempFunction(parentScope);");
            if(result===false) return false;
            return true;
        },
        getButtonStyle:function(alias){
            var  buttonsStyle = {
                "start":{css:"btn btn-success fa fa-send",dialogHeigth:422,dialogWidth:790},
                "draft":{css:"btn btn-primary fa fa-clipboard"},
                "save":{css:"btn btn-primary fa fa-clipboard"},
                "agree":{css:"btn btn-success fa fa-check-square-o",dialogHeigth:422,dialogWidth:790},
                "oppose":{css:"btn btn-primary fa fa-close",dialogHeigth:422,dialogWidth:650},
                "reject":{css:"btn btn-danger fa fa-lastfm",dialogHeigth:422,dialogWidth:650},
                "reject2Start":{css:"btn btn-danger fa fa-lastfm",dialogHeigth:422,dialogWidth:650},
                "lock":{css:"btn btn-primary fa fa-lock"},
                "unlock":{css:"btn btn-primary fa fa-unlock"},
                "taskOpinion":{css:"btn btn-primary fa fa-navicon",dialogHeigth:'80%',dialogWidth:'75%'},
                "flowImage":{css:"btn btn-primary fa fa-image",dialogHeigth:'80%',dialogWidth:'90%'},
                "manualEnd":{css:"btn btn-danger fa fa-ioxhost",dialogHeigth:322,dialogWidth:690},
                "print":{css:"btn btn-primary fa fa-print",dialogHeigth:300,dialogWidth:500},
                'recall': { css: 'btn btn-warning fa fa-undo', dialogHeigth: 422, dialogWidth: 650 },
                'recover': { css: 'btn btn-danger fa fa-reply-all', dialogHeigth: 422, dialogWidth: 650 },
                'reminder': { css: 'btn btn-warning fa fa-bell-o', dialogHeigth: 422, dialogWidth: 650 },
                'revoke': { css: 'btn btn-danger fa fa-undo', dialogHeigth: 422, dialogWidth: 690 }
            }
            if(buttonsStyle[alias]) return  buttonsStyle[alias];
            return {css:"btn btn-success "};
        }
    },
    template:'<div>                                                                                     						\
		 			<span v-for="btn in buttons" :class="getButtonStyle(btn.alias).css" v-on:click="buttonClick(btn)" style="margin-right: 5px;">                                            \
		 			{{btn.name}}</span>                                                               							\
	 		  </div>',

});

function getCustFormComponent(pageComponent){
    for(var i=0,c;c=pageComponent.$children[i++];){
        if(c.$options._componentTag==="ab-custom-form"){
            return c;
        }
        // url 琛ㄥ崟鍒欒繑鍥炵埗椤甸潰
        if(c.$options._componentTag==="ab-url-form"){
            return pageComponent;
        }
    }
    // 涓嶅悜涓嬮€掑綊
    console.error("椤甸潰涓壘涓嶅埌 cust-form 鐨勭粍浠讹紒锛侊紒");
    return null;
}